import { forEach } from 'src/utils/index';
import { isArray, isDate, isObj } from 'src/utils/validate/data.js';

function encode(val) {
	return encodeURIComponent(val)
		.replace(/%40/gi, '@')
		.replace(/%3A/gi, ':')
		.replace(/%24/g, '$')
		.replace(/%2C/gi, ',')
		.replace(/%20/g, '+')
		.replace(/%5B/gi, '[')
		.replace(/%5D/gi, ']');
}

export const processUrl = (url, params, paramsSerializer) => {
	/*eslint no-param-reassign:0*/
	if (!params) {
		return url;
	}

	var serializedParams;
	if (paramsSerializer) {
		serializedParams = paramsSerializer(params);
	} else {
		// else if (utils.isURLSearchParams(params)) {
		//   serializedParams = params.toString();
		// }
		var parts = [];

		forEach(params, function serialize(val, key) {
			if (val === null || typeof val === 'undefined') {
				return;
			}

			if (isArray(val)) {
				key = key + '[]';
			} else {
				val = [val];
			}

			forEach(val, function parseValue(v) {
				if (isDate(v)) {
					v = v.toISOString();
				} else if (isObj(v)) {
					v = JSON.stringify(v);
				}
				parts.push(encode(key) + '=' + encode(v));
			});
		});

		serializedParams = parts.join('&');
	}

	if (serializedParams) {
		var hashmarkIndex = url.indexOf('#');
		if (hashmarkIndex !== -1) {
			url = url.slice(0, hashmarkIndex);
		}

		url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
	}

	return url;
};

export const bind = (fn, thisArg) => {
	return function wrap() {
		var args = new Array(arguments.length);
		for (var i = 0; i < args.length; i++) {
			args[i] = arguments[i];
		}
		return fn.apply(thisArg, args);
	};
};
/**
 * Creates a new URL by combining the specified URLs
 *
 * @param {string} baseURL The base URL
 * @param {string} relativeURL The relative URL
 * @returns {string} The combined URL
 */
export const combineURLs = (baseURL, relativeURL) => {
	return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL;
};
